import { _decorator, Component, instantiate, Node, Prefab, UITransform, Vec2, Vec3 } from 'cc';
const { ccclass, property } = _decorator;

@ccclass('main')
export class main extends Component {

    @property(Node)
    content: Node = null;

    @property(Prefab)
    item: Prefab = null;

    public iconRowNum = 6;
    public iconColNum = 4;
    public iconTotalNum = 0;
    public iconArr = [[], [], [], [], [], []];

    start() {
        this.initGame();
    }
    // 初始化游戏
    initGame () {
        this.iconTotalNum = 0;
        this.iconArr = [[], [], [], [], [], []];
        this.initIcon();
    }
    // 更新icon
    updateIcon() {
        this.initIcon();
    }
    // 初始化icon
    initIcon() {
        this.createRowIcon();
        let timer = setInterval(() => {
            if (this.iconTotalNum < this.iconColNum * this.iconRowNum) this.createRowIcon();
            else clearInterval(timer), timer = null, this.destroyIcon();
        }, 2000);
    }
    // 销毁icon
    destroyIcon() {
        // 消除icon
        this.content.removeAllChildren();
        // icon下移
        // 重新生成新的icon
        setTimeout(() => {
            this.initGame();
        }, 1000);
    }
    // 创建一排icon
    public createRowIcon() {
        for (let i = 0; i < this.iconArr.length; i++) {
            if (this.iconArr[i].length < this.iconColNum && this.iconTotalNum < this.iconColNum * this.iconRowNum) this.createIcon(i);
        }
    }
    // 创建单个icon
    public createIcon(index) {
        const item = instantiate(this.item);
        const target = this.getItemPosition(index);
        const iconIndex = this.getRandomInteger(0, 12);
        this.iconTotalNum += 1;
        this.iconArr[index].push(iconIndex);
        item.active = !0;
        item.getChildByName('symbols').getChildByName(`symbol_${ iconIndex }`).active = !0;
        // item.getChildByName(`symbol_${ iconIndex }`).getComponent(UITransform).width = target.width;
        // item.getChildByName(`symbol_${ iconIndex }`).getComponent(UITransform).height = target.height;
        item.setScale(new Vec3(0.8, 0.8, 0.8));
        item.setPosition(target.x, target.y);
        item.getComponent('item').posY = - (this.content.getComponent(UITransform).height / 2 - target.height / 2) + (this.iconArr[index].length - 1) * target.height;
        this.content.addChild(item);
    }
    // 获取icon位置
    protected getItemPosition(index) {
        const C_W = this.content.getComponent(UITransform).width;
        const C_H = this.content.getComponent(UITransform).height;
        const I_W = C_W / 6;
        const I_h = C_H / 4;
        return {
            width: I_W,
            height: I_h,
            x: -(C_W / 2 - I_W / 2) + I_W * index,
            y: (C_H / 2 - I_h / 2),
        }
    }
    // 获取随机值
    public getRandomInteger(min, max) {
        return Math.floor(Math.random() * (max - min + 1)) + min;
    }

    update(deltaTime: number) {
        
    }
}


